package org.example;

import java.util.concurrent.CountDownLatch;

public class CountDownLatchExample {
    public static void main(String[] args) throws InterruptedException {
        int threadCount = 3;
        CountDownLatch latch = new CountDownLatch(threadCount);

        for (int i = 0; i < threadCount; i++) {
            new Thread(() -> {
                try {
                    // 模拟任务
                    Thread.sleep((long) (Math.random() * 1000));
                    System.out.println("Task completed by " + Thread.currentThread().getName());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    latch.countDown(); // 每个线程完成任务后，计数减1
                }
            }).start();
        }

        latch.await(); // 主线程等待
        System.out.println("All tasks completed!");
    }
}
